import { defineStore } from 'pinia';
import { ref } from 'vue';
import { loginAPI } from '@/apis/user';
import { mergeCartAPI } from '@/apis/cart.js';
import { useCartStore } from './cartStore.ts';

export const useUserStore = defineStore(
  'user',
  () => {
    // 准备响应式数据
    const userInfo = ref({});
    const cartStore = useCartStore();
    const getUserInfo = async ({ account, password }) => {
      const cartStore = useCartStore();
      const res = await loginAPI({ account, password });
      console.log(res);
      userInfo.value = res.data.result;

      // 登录成功后，合并购物车
      const items = cartStore.cartList.map((item) => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count,
        };
      });
      await mergeCartAPI(items);
      // 更新数据
      cartStore.updateNewList();
    };

    const clearUserInfo = () => {
      userInfo.value = {};
    };

    //退出登录，数据清空  stores/user.js
    const clearData = () => {
      //用户数据清空
      userInfo.value = {};
      //购物车清空
      cartStore.clearCart();
    };

    return { userInfo, getUserInfo, clearUserInfo, clearData };
  },
  {
    persist: true,
  },
);
